#include "qso_edit_dialog.h"
#include "ui_manager.h"
#include "../database/sqlite_manager.h"
#include "../app/main_app.h"
#include <iostream>

QSOEditDialog::QSOEditDialog() {
    builder = nullptr;
    window = nullptr;
}

QSOEditDialog::~QSOEditDialog() {
    if (builder) {
        g_object_unref(builder);
    }
}

bool QSOEditDialog::init(const QSORecord& record) {
    record_ = record;
    
    // 创建GtkBuilder
    builder = gtk_builder_new();
    
    // 获取UI文件路径
    std::string ui_path = UIManager::get_ui_path();
    // 替换main.glade为qso_edit_dialog.glade
    size_t pos = ui_path.find_last_of("/");
    if (pos != std::string::npos) {
        ui_path = ui_path.substr(0, pos) + "/qso_edit_dialog.glade";
    } else {
        ui_path = "UI/qso_edit_dialog.glade";
    }
    
    // 从文件加载UI
    GError *error = nullptr;
    if (!gtk_builder_add_from_file(builder, ui_path.c_str(), &error)) {
        std::cerr << "无法加载UI文件 " << ui_path << ": " << error->message << std::endl;
        g_error_free(error);
        g_object_unref(builder);
        builder = nullptr;
        return false;
    }
    
    // 获取窗口对象
    window = GTK_WIDGET(gtk_builder_get_object(builder, "qso_edit_dialog"));
    if (!window) {
        std::cerr << "无法获取qso_edit_dialog对象" << std::endl;
        g_object_unref(builder);
        builder = nullptr;
        return false;
    }
    
    // 将this指针存储在窗口对象中，以便在信号处理函数中获取
    g_object_set_data(G_OBJECT(window), "qso_edit_dialog_instance", this);
    
    // 连接信号
    // 注册信号处理函数
    gtk_builder_add_callback_symbol(builder, "on_save_button_clicked", G_CALLBACK(on_save_button_clicked));
    gtk_builder_add_callback_symbol(builder, "on_cancel_button_clicked", G_CALLBACK(on_cancel_button_clicked));
    
    gtk_builder_connect_signals(builder, nullptr);
    
    // 填充字段数据
    populate_fields();
    
    return true;
}

void QSOEditDialog::show() {
    if (window) {
        gtk_widget_show_all(window);
    }
}

void QSOEditDialog::hide() {
    if (window) {
        gtk_widget_hide(window);
    }
}

GtkWidget* QSOEditDialog::get_window() {
    return window;
}

void QSOEditDialog::populate_fields() {
    // 填充各个字段
    GtkWidget *entry;
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_date"));
    if (entry) {
        gtk_entry_set_text(GTK_ENTRY(entry), record_.date.c_str());
    }
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_time"));
    if (entry) {
        gtk_entry_set_text(GTK_ENTRY(entry), record_.time.c_str());
    }
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_callsign"));
    if (entry) {
        gtk_entry_set_text(GTK_ENTRY(entry), record_.callsign.c_str());
    }
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_band"));
    if (entry) {
        gtk_entry_set_text(GTK_ENTRY(entry), record_.band.c_str());
    }
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_frequency"));
    if (entry) {
        gtk_entry_set_text(GTK_ENTRY(entry), record_.frequency.c_str());
    }
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_mode"));
    if (entry) {
        gtk_entry_set_text(GTK_ENTRY(entry), record_.mode.c_str());
    }
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_rst_sent"));
    if (entry) {
        gtk_entry_set_text(GTK_ENTRY(entry), record_.rst_sent.c_str());
    }
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_rst_rcvd"));
    if (entry) {
        gtk_entry_set_text(GTK_ENTRY(entry), record_.rst_rcvd.c_str());
    }
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_name"));
    if (entry) {
        gtk_entry_set_text(GTK_ENTRY(entry), record_.name.c_str());
    }
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_qth"));
    if (entry) {
        gtk_entry_set_text(GTK_ENTRY(entry), record_.qth.c_str());
    }
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_memo"));
    if (entry) {
        gtk_entry_set_text(GTK_ENTRY(entry), record_.memo.c_str());
    }
}

bool QSOEditDialog::validate_fields() {
    // 简单验证：检查必要字段是否为空
    GtkWidget *entry_callsign = GTK_WIDGET(gtk_builder_get_object(builder, "entry_callsign"));
    if (entry_callsign) {
        const char* callsign = gtk_entry_get_text(GTK_ENTRY(entry_callsign));
        if (strlen(callsign) == 0) {
            std::cerr << "呼号不能为空" << std::endl;
            return false;
        }
    }
    
    return true;
}

bool QSOEditDialog::save_record() {
    // 验证字段
    if (!validate_fields()) {
        return false;
    }
    
    // 从界面获取数据更新record_
    GtkWidget *entry;
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_date"));
    if (entry) {
        record_.date = gtk_entry_get_text(GTK_ENTRY(entry));
    }
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_time"));
    if (entry) {
        record_.time = gtk_entry_get_text(GTK_ENTRY(entry));
    }
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_callsign"));
    if (entry) {
        record_.callsign = gtk_entry_get_text(GTK_ENTRY(entry));
    }
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_band"));
    if (entry) {
        record_.band = gtk_entry_get_text(GTK_ENTRY(entry));
    }

    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_frequency"));
    if (entry) {
        record_.frequency = gtk_entry_get_text(GTK_ENTRY(entry));
    }
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_mode"));
    if (entry) {
        record_.mode = gtk_entry_get_text(GTK_ENTRY(entry));
    }
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_rst_sent"));
    if (entry) {
        record_.rst_sent = gtk_entry_get_text(GTK_ENTRY(entry));
    }
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_rst_rcvd"));
    if (entry) {
        record_.rst_rcvd = gtk_entry_get_text(GTK_ENTRY(entry));
    }
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_name"));
    if (entry) {
        record_.name = gtk_entry_get_text(GTK_ENTRY(entry));
    }
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_qth"));
    if (entry) {
        record_.qth = gtk_entry_get_text(GTK_ENTRY(entry));
    }
    
    entry = GTK_WIDGET(gtk_builder_get_object(builder, "entry_memo"));
    if (entry) {
        record_.memo = gtk_entry_get_text(GTK_ENTRY(entry));
    }
    
    // 保存到数据库
    SQLiteManager& dbManager = SQLiteManager::getInstance();
    if (!dbManager.connect()) {
        std::cerr << "无法连接到数据库" << std::endl;
        return false;
    }
    
    bool result;
    if (record_.id.empty()) {
        // 新记录
        result = dbManager.insertQSO(record_);
    } else {
        // 更新记录
        result = dbManager.updateQSO(record_);
    }
    
    if (result) {
        std::cout << "记录保存成功" << std::endl;
        // 刷新log_grid_dialog中的treeview
        // 通过MainApp类的公共方法访问logWindowInstance
        LogGridDialog* logWindow = MainApp::getLogWindowInstance();
        if (logWindow) {
            logWindow->populate_log_data();
        }
    } else {
        std::cerr << "记录保存失败" << std::endl;
    }
    
    return result;
}

// "保存"按钮点击处理函数
void QSOEditDialog::on_save_button_clicked(GtkButton *button, gpointer data) {
    // 通过窗口对象获取QSOEditDialog实例
    GtkWidget *window = GTK_WIDGET(gtk_widget_get_toplevel(GTK_WIDGET(button)));
    if (window) {
        QSOEditDialog *dialog = static_cast<QSOEditDialog*>(g_object_get_data(G_OBJECT(window), "qso_edit_dialog_instance"));
        if (dialog) {
            if (dialog->save_record()) {
                // 保存成功，关闭对话框
                dialog->hide();
            }
        }
    }
}

// "取消"按钮点击处理函数
void QSOEditDialog::on_cancel_button_clicked(GtkButton *button, gpointer data) {
    // 通过窗口对象获取QSOEditDialog实例
    GtkWidget *window = GTK_WIDGET(gtk_widget_get_toplevel(GTK_WIDGET(button)));
    if (window) {
        QSOEditDialog *dialog = static_cast<QSOEditDialog*>(g_object_get_data(G_OBJECT(window), "qso_edit_dialog_instance"));
        if (dialog) {
            dialog->hide();
        }
    }
}